//
//  WithdrawFundsViewController.m
//  DaJiang
//
//  Created by sally on 16/10/6.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "CashModel.h"
#import "CellManager.h"
#import "WithdrawFundsCell.h"
#import "WithdrawFundsViewController.h"

@interface WithdrawFundsViewController ()

@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UILabel *cashLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *tableData;
@property (strong, nonatomic) NSMutableArray *withdrawData; //提现数据
@property (strong, nonatomic) UITextField *alipayTextField;
@property (strong, nonatomic) UITextField *cashTextField;
@property (strong, nonatomic) NSString *alipay;
@property (strong, nonatomic) NSString *cash;

@end

@implementation WithdrawFundsViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setNotification];
  [self initControl];
  [self initData];
  [self loadData];
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark 设置通知
- (void)setNotification {
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

#pragma mark 初始化控件
- (void)initControl {
  self.title = @"余额提现";
  self.headerView.height = GHeadViewHeight;
  [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}

#pragma mark 初始化数据
- (void)initData {
  self.tableData = [NSMutableArray array];
  self.withdrawData = [NSMutableArray array];
  [self.tableData addObject:@[ @"支付宝账号" ]];
  [self.tableData addObject:@[ @"提现金额" ]];
  [self.tableData addObject:@[ @"转账记录" ]];
  [self initControlText];
}

#pragma mark 初始化控件数据
- (void)initControlText {
  UserModel *user = [[CacheManager shareInstance] getLastLoginAccount];
  self.alipay = user.user_data.alipay;
  self.cash = @"";
}

#pragma mark 获取数据
- (void)loadData {
  [[CommonMethod sharedCommonMethod] createProgressHUDInView:self.view withMessage:@""];

  [CashModel queryCashAccountWithCompletion:^(CashModel *cashModel) {
    if (cashModel) {
      CashSummaryModel *cashSummary = [cashModel.account_summary firstObject];
      self.cashLabel.text = [NSString stringWithFormat:@"¥%.2f", cashSummary.value];
      [self.withdrawData removeAllObjects];
      [self.withdrawData addObjectsFromArray:cashModel.account_log];
      self.cash = @"";
      [self.tableView reloadData];
    } else {
      NSError *error = [CashModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
  }];
}

#pragma mark - action
#pragma mark 点击确认转出
- (IBAction)actionOnSure:(id)sender {
  if (self.alipay.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入支付宝账号"];
    return;
  }
  if (self.cash.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入提现金额"];
    return;
  }
  if (![OperationManager validateMoney:self.cash]) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入正常格式的提现金额"];
    return;
  }
  if ([self.cash floatValue] <= 0) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入大于0的提现金额"];
    return;
  }
  
  [[CommonMethod sharedCommonMethod] createProgressHUDInView:self.view withMessage:@""];
  UserModel *user = [[CacheManager shareInstance] getLastLoginAccount];
  
  //如果本地缓存的支付宝账号和输入账号不一致，则重新绑定支付宝
  if (![user.user_data.alipay isEqualToString:self.alipay]) {
    [UserModel bindAlipayWithAlipay:self.alipay completion:^(UserModel *user) {
      if (user) {
        
        //更新本地用户信息缓存中的支付宝账号
        UserModel *locUser = [[CacheManager shareInstance]getLastLoginAccount];
        locUser.user_data.alipay = user.user_data.alipay;
        [[CacheManager shareInstance]cacheLastLoginAccount:locUser];
        
        //提现
        [self takeCash];
        
      } else {
        NSError *error = [UserModel getLastError];
        [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
      }
    }];
  }else{
    //提现
    [self takeCash];
  }

}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return self.tableData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  if (section == 2) { //转账记录
    return self.withdrawData.count + 1;
  } else {
    return [[self.tableData objectAtIndex:section] count];
  }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  return 0.1; //section头部高度
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
  return GNormalMargin; //section底部高度
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (indexPath.section == 2 && indexPath.row != 0) { //转账记录
    return GMineHeadCellHeight;
  }
  return NavHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  if (indexPath.section == 2 && indexPath.row != 0) { //转账记录

    WithdrawFundsCell *cell = (WithdrawFundsCell *) [tableView dequeueReusableCellWithIdentifier:@"WithdrawFundsCell"];
    if (!cell) {
      cell = [[[NSBundle mainBundle] loadNibNamed:@"WithdrawFundsCell" owner:nil options:nil] lastObject];
    }
    cell.cellData = [self.withdrawData objectAtIndex:indexPath.row - 1];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;

  } else {

    UITableViewCell *cell;
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    //向右箭头，列表项点击性
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    //主标题
    [CellManager configCellNormalText:cell];
    cell.textLabel.text = [[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

    //编辑行
    if (indexPath.section != 2) {
      UITextField *textField = [CellManager configCellNormalTextField:cell];
      textField.tag = indexPath.section;
      [cell.contentView addSubview:textField];
      if (indexPath.section == 0) {//支付宝账号
        textField.text = self.alipay;
        self.alipayTextField = textField;
      } else {//金额
        textField.text = self.cash;
        textField.keyboardType = UIKeyboardTypeDecimalPad;
        self.cashTextField = textField;
      }
    }
    return cell;
  }
}

#pragma mark - 私有方法
#pragma mark textfield中的文本发生改变时
- (void)textFieldChanged:(NSNotification *)notification {
  UITextField *textField = (UITextField *)notification.object;
  if ([textField isEqual:self.alipayTextField]) {
    self.alipay = textField.text;
  }else if ([textField isEqual:self.cashTextField]){
    self.cash = textField.text;
  }
}

#pragma mark 提现操作
-(void)takeCash{
  [CashSummaryModel takeCashWithValue:self.cash completion:^(CashSummaryModel *summaryModel) {
    if (summaryModel) {
      [[CommonMethod sharedCommonMethod]showAlertMessage:@"已提现，请等候到账"];
      //刷新数据和界面
      [self loadData];
    } else {
      NSError *error = [CashSummaryModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
  }];
}

@end
